package com.langChain4j.model.config;

import com.langChain4j.api.entity.AgentDialogSession;
import com.langChain4j.api.enums.SessionEnum;
import com.langChain4j.conversation.service.AgentConversationService;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author linjun
 * @date 2025/10/11 11:18
 * @description
 */
@Service
public class DBChatMemoryStore implements ChatMemoryStore {

    @Autowired
    private AgentConversationService conversationService;

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        AgentDialogSession dialogSession = conversationService.queryBySessionId(memoryId.toString());
        List<ChatMessage> historyMessage = new ArrayList<>();
        if (StringUtils.isNotBlank(dialogSession.getContextMemory())) {
            List<ChatMessage> messages = ChatMessageDeserializer.messagesFromJson(dialogSession.getContextMemory());
            historyMessage.addAll(messages);
        }
        return historyMessage;
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        // 更新会话上下文（模拟）
        AgentDialogSession dialogSession = conversationService.queryBySessionId((String) memoryId);
        dialogSession.setContextMemory(ChatMessageSerializer.messagesToJson(messages));
        dialogSession.setUpdateTime(LocalDateTime.now());
        conversationService.updateById(dialogSession);
    }

    @Override
    public void deleteMessages(Object memoryId) {
        AgentDialogSession session = conversationService.queryActiveBySessionId((String) memoryId);
        // 设置会话结束时间并标记为完成状态
        session.setEndTime(LocalDateTime.now());
        session.setStatus(SessionEnum.SESSION_STATUS_END.getCode());
        session.setUpdateTime(LocalDateTime.now());
    }
}
